package com.atguigu.binaryTree;

import java.util.LinkedList;
import java.util.Queue;

public class SerializeAndDeserialize {
    //反序列化，翻译字符串为二叉树
    public static TreeNode deserialize(String str){
        String[] values=str.split("_");
        Queue<String> queue=new LinkedList<>();
        for(int i=0;i<values.length;i++){
            queue.add(values[i]);
        }
        return reconPreOrder(queue);
    }
    public static TreeNode reconPreOrder(Queue<String> queue){
        String value=queue.poll();
        if(value.equals("#")){
            return null;
        }
        TreeNode head=new TreeNode(Integer.valueOf(value));
        head.left=reconPreOrder(queue);
        head.right=reconPreOrder(queue);
        return head;
    }
    //序列化字符串的过程
    public static String serialize(TreeNode root){ //序列化字符串
        if(root==null){
            return "#_";
        }
        String res=root.val+"_";
        res+=serialize(root.left);
        res+=serialize(root.right);
        return res;
    }
}
